const connection = require('../app/database');
class CommentService {
  async create (momentId, content, id) {
    const statement = `INSERT INTO comment (content, moment_id, user_id) VALUES (?, ?, ?);`;
    const [result] = await connection.execute(statement, [content, momentId, id])
    return result;
  }
  async reply (momentId, content, id, commendId) {
   try {
    const statement = `INSERT INTO comment (content, moment_id, user_id, comment_id) VALUES (?, ?, ?, ?);`;
    const [result] = await connection.execute(statement, [content, momentId, id, commendId])
    return result;
   } catch (err) {
     console.log(err);
   }
  }
  async update (momentId, content) {
    const statement = `UPDATE comment SET content = ? WHERE id = ?;`;
    const [result] = await connection.execute(statement, [content, momentId]);
    return result;
  }
  async remove (commentId) {
    const statement = `DELETE FROM comment WHERE id = ?;`;
    const [result] = await connection.execute(statement, [commentId]);
    return result;
  }
  async getCommentsByMomentId (id) {
    const statement = `
      SELECT
        m.id, m.content, m.comment_id commentId, m.createAt createTime,
        JSON_OBJECT('id', u.id, 'name', u.name) user
      FROM comment m
      LEFT JOIN users u ON u.id = m.user_id
      WHERE m.moment_id = ?;
    `;
    const [result] = await connection.execute(statement, [id]);
    return result;
  }
}


module.exports = new CommentService();